--- 模块功能：MQTT客户端处理框架
-- @author openLuat
-- @module mqtt.mqttTask
-- @license MIT
-- @copyright openLuat
-- @release 2018.03.28
module(..., package.seeall)

require "misc"
require "mqtt"
require "mqttInMsgCMD"
require "logGenerator"
require "mqttOutMsgCMD"
--参数初始化
local ready = false

--- MQTT连接是否处于激活状态
-- @return 激活状态返回true，非激活状态返回false
-- @usage mqttTask.isReady()
function isReady() return ready end

-- 启动MQTT客户端任务
sys.taskInit(function()
    local retryConnectCnt, retryStartDevCnt = 0, 0
    while true do
        if not socket.isReady() then
            retryConnectCnt = 0
            -- 等待网络环境准备就绪，超时时间是5分钟
            sys.waitUntil("IP_READY_IND", 300000)
            log.info("retryStartDevCnt加1")
            retryStartDevCnt = retryStartDevCnt + 1
        end
        if socket.isReady() then
            retryStartDevCnt = 0
            log.info("imei", misc.getImei())
            -- 创建一个MQTT客户端
            local mqttClient = mqtt.client(misc.getImei(), 60, "admin", "keson-123", nil, nil, "3.1.1")
            if mqttClient:connect("47.94.80.3", 61613, "tcp") then
                retryConnectCnt = 0
                ready = true
                -- 订阅主题
                if mqttClient:subscribe({ ["guard"] = 0 }) then
                    -- 循环处理接收和发送的数据
                    while true do
                        if not mqttInMsgCMD.proc(mqttClient) then
                            log.error("mqttTask.mqttInMsg.proc error")
                            break
                        end
                        if not mqttOutMsgCMD.proc(mqttClient) then log.error("mqttTask.mqttOutMsg proc error") break end
                    end
                end
                ready = false
            else
                retryConnectCnt = retryConnectCnt + 1
            end
            -- 断开MQTT连接
            mqttClient:disconnect()
            if retryConnectCnt >= 5 then
                link.shut()
                retryConnectCnt = 0
            end
            sys.wait(500)
        else
            -- 进入飞行模式，20秒之后，退出飞行模式
            net.switchFly(true)
            sys.wait(20000)
            net.switchFly(false)
        end
        if retryStartDevCnt >= 7 then
            retryStartDevCnt = 0
            sys.restart("重启设备！")
        end
    end
end)
